const express = require('express')

const router = express.Router()

const {db,genid} = require('../db/DbUtils')

//添加接口
router.post('/_token/add',async (req,res)=>{

    let {name} = req.body
    const insert_sql = 'insert into `category` (`id`,`name`) values (?,?)'
    let{err,rows}=await db.async.run(insert_sql,[genid.NextId(),name])

    //没有进行异常数据的校验 
    if(err == null){
        res.send({
            code:200,
            msg:'添加成功',

        })
    }else{
        res.send({
            code:500,//可以协商自定义
            msg:'添加失败',
            
        })
    }
})

//修改接口
router.put('/_token/update',async (req,res)=>{

    let {id,name} = req.body
    const update_sql ='update `category` set `name` = ? where `id` = ?'
    let {err,rows}=await db.async.run(update_sql,[name,id])

    //没有进行异常数据的校验 需要学习数据库sqlite语句后补充
    if(err == null ){
        res.send({
            code:200,
            msg:'修改成功',

        })
    }else{
        res.send({
            code:500,
            msg:'修改失败',
            
        })
    }
})
//删除接口 
router.delete('/_token/delete',async (req,res)=>{
    // /category/delete?id=xxx

    let id= req.query.id
    const delete_sql ='delete from `category` where `id` = ?'
    let {err,rows}=await db.async.run(delete_sql,[id])

    //没有进行异常数据的校验 
    if(err == null){
        res.send({
            code:200,
            msg:'删除成功',

        })
    }else{
        res.send({
            code:500,
            msg:'删除失败',
            
        })
    }
})

//列表接口(简化了查询 分页分类?(分类不多)全查)
router.get('/list',async (req,res)=>{

    const search_sql ='select * from `category`'
    let {err,rows}= await db.async.all(search_sql,[])

    if(err == null){
        res.send({
            code:200,
            msg:'查询成功',
            rows,

        })
    }else{
        res.send({
            code:500,
            msg:'查询失败',
            
        })
    }
})

module.exports = router